package com.lcz.authority.admin.controller.monitor;


import com.github.pagehelper.PageInfo;
import com.lcz.authority.admin.service.SysUserOnlineService;
import com.lcz.authority.common.constant.CacheConstants;
import com.lcz.authority.common.constant.HttpStatus;
import com.lcz.authority.common.core.RedisCache;
import com.lcz.authority.common.core.page.TableDataInfo;
import com.lcz.authority.common.domain.AjaxResult;
import com.lcz.authority.common.domain.model.LoginUser;
import com.lcz.authority.common.domain.vo.SysUserOnline;
import com.lcz.authority.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @author lcz
 * @desc 在线用户监控
 * @mail lcz_0130@163.com
 * @date 2024/05/16
 */
@RestController
@RequestMapping("/monitor/online")
public class SysUserOnlineController {
    @Autowired
    private SysUserOnlineService userOnlineService;

    @Autowired
    private RedisCache redisCache;

    @PreAuthorize("@ss.hasPermi('monitor:online:list')")
    @GetMapping("/list")
    public TableDataInfo list(String loginLocation, String userName) {
        Collection<String> keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        List<SysUserOnline> userOnlineList = new ArrayList<>();
        for (String key : keys) {
            LoginUser user = redisCache.getCacheObject(key);
            if (StringUtils.isNotEmpty(loginLocation) && StringUtils.isNotEmpty(userName)) {
                userOnlineList.add(userOnlineService.selectOnlineByInfo(loginLocation, userName, user));
            } else if (StringUtils.isNotEmpty(loginLocation)) {
                userOnlineList.add(userOnlineService.selectOnlineByIpaddr(loginLocation, user));
            } else if (StringUtils.isNotEmpty(userName) && StringUtils.isNotNull(user.getUser())) {
                userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user));
            } else {
                userOnlineList.add(userOnlineService.loginUserToUserOnline(user));
            }
        }
        Collections.reverse(userOnlineList);
        userOnlineList.removeAll(Collections.singleton(null));
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(userOnlineList);
        rspData.setTotal(new PageInfo(userOnlineList).getTotal());
        return rspData;
    }

    /**
     * 强退用户
     */
    @PreAuthorize("@ss.hasPermi('monitor:online:forceLogout')")
    @DeleteMapping("/{tokenId}")
    public AjaxResult forceLogout(@PathVariable String tokenId) {
        redisCache.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + tokenId);
        return AjaxResult.success();
    }
}
